package handler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"order-perm/cache"
	"order-perm/model"
	"strconv"
	"time"
)

func Shopadd(c *gin.Context) {
	name := c.PostForm("name")
	price := c.PostForm("price")
	if name == "" || price == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "参数不能为空",
		})
		return
	}
	shop := model.Shop{
		Name:  name,
		Price: price,
	}
	err := model.DB.Create(&shop).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}
func ShopOrderlist(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "5"))
	oid, _ := strconv.Atoi(c.Query("oid"))
	offset := (page - 1) * size
	/*
				SELECT
		*
		FROM
		shops
		LEFT JOIN shop_orders ON shops.id=shop_orders.id
		WHERE shop_orders.oid=1
	*/
	var shop []model.Shop
	model.DB.Table("shops").
		Joins("LEFT JOIN shop_orders ON shops.id=shop_orders.id").
		Where("shop_orders.oid=?", oid).
		Offset(offset).
		Limit(size).
		Find(&shop)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": shop,
	})
	return
}
func List(c *gin.Context) {
	var order []model.Order
	redis_key := "list_"
	errcache, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if errcache == "" {
		model.DB.Find(&order)
		jsonData, _ := json.Marshal(order)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(errcache), &order)
	}

	c.JSON(200, gin.H{
		"code": 500,
		"msg":  "查询成功",
		"data": order,
	})
	return
}
func Detail(c *gin.Context) {
	id := c.Query("id")
	var order []model.Order
	model.DB.Where("id=?", id).Find(&order)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": order,
	})
	return
}
func Detailredis(c *gin.Context) {
	id := c.Query("id")
	var order []model.Order
	redis_key := "detail_" + id
	errcache, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if errcache == "" {
		model.DB.Where("id=?", id).Find(&order)
		jsonData, _ := json.Marshal(order)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(errcache), &order)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": order,
	})
	return
}
